package com.example.demo10;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.demo10.R;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private static final String HTTPULR = "http://blog.beaa.xyz/";
    private Button btn_get;
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn_get=findViewById(R.id.btn_get);
        text=findViewById(R.id.text);


        //点击获取网络源码,并显示
        btn_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(() -> {
                    try {
                        //创建一个URl对象
                        URL url=new URL(HTTPULR);
                        //用url，创建HttpURLConnection对象进行对网络的操作
                        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                        //指定请求方式
                        conn.setRequestMethod("GET");
                        //设置超时的时间
                        conn.setConnectTimeout(30000);
                        //获取请求数据(流类型)
                        InputStream inputStream = conn.getInputStream();
                   /*
                        将流数据转换成字符串
                    */
                        StringBuilder buffer= new StringBuilder();
                        String line;
                        BufferedReader dr=new BufferedReader(new InputStreamReader(inputStream));
                        while ((line=dr.readLine())!=null)
                        {
                            buffer.append(line);
                        }
                        String str=buffer.toString();
                        Log.d("信息",str);
                        //显示内容，（开启异步线程更新主界面的ui）
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                text.setText(str);
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        });
    }
}